package cn.tqfeiyang.springplus.generator.util;

import net.sf.cglib.core.ReflectUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

/**
 * 对象工具类
 *
 * @author tqfeiyang
 * @since 2024/10/19 11:35
 */
public class ObjectUtils {

    public static String get(Object target, String path) {
        if (Objects.isNull(target)) {
            return "";
        }

        String[] items = StringUtils.split(path, ".", 2);
        String current = null, child = null;
        if (items.length >= 2) {
            current = items[0];
            child = StringUtils.join(items, ".", 1, items.length).toString();
        } else {
            current = path;
        }

        Object value = null;
        if (target instanceof Map<?,?>) {
            value = ((Map<?, ?>) target).get(current);
        } else {
            value = getValue(target, current);
        }

        if (Objects.nonNull(value)) {
            if (StringUtils.isNotBlank(child)) {
                return get(value, child);
            } else {
                return value.toString();
            }
        } else {
            return "";
        }
    }

    private static Object getValue(Object target, String name) {
        try {
            Field field = target.getClass().getDeclaredField(name);
            field.setAccessible(true);
            return field.get(target);
        } catch (Exception e) {
            return null;
        }
    }
}
